from mx.DateTime import DateFrom, DateTimeFrom
from RDF import Statement, SPARQLQuery

nsmap = {'dc':'http://purl.org/dc/elements/1.1/'}

class Node(object):
	def __init__(self, uri):
		self.uri = uri
	def find(self, model, resource):
		s = Statement(resource, self.uri, None)
		for r in model.find_statements(s):
			return r.object
	def __call__(self, model, resource):
		return self.find(model, resource)

class Resource(Node):
	def __init__(self, uri, model):
		self.uri = uri
		self.model = model
	def __call__(self, model, resource):
		node = Node.__call__(self, model, resource)
		if node:
			assert(node.is_resource())
			manager = self.model._default_manager
			obj, created = manager.rdf_get_or_create(model, node)
			return obj
	
class Literal(Node):
	def __call__(self, model, resource):
		node = Node.__call__(self, model, resource)
		if node:
			assert(node.is_literal())
			return node.literal_value["string"]

class String(Literal):
	"""
	Regular String
	"""
         	
class Integer(Literal):
	"""
	Integer Value
	"""
	def __call__(self, model, resource):
		s = Literal.__call__(self, model, resource)
		return int(s)

class Date(Literal):
	"""
	Date Type
	"""
	def __call__(self, model, resource):
		s = Literal.__call__(self, model, resource)
		return DateFrom(str(s))

class DateTime(Literal):
	"""
	Date Time Type
	"""
	def __call__(self, model, resource):
		s = Literal.__call__(self, model, resource)
		return DateTimeFrom(str(s))

def coordinates_wkt(polystr):
    """
    Helper function. Probably does not belong here. Returns WKT
    content for a list of coordinates, one per line.
    """
    def _f():
        for line in str(polystr).split('\n'):
            point = line.strip().replace(' ', '').replace(',', ' ')
            if point:
                yield point
    polygon = '(' + ', '.join(list(_f())) + ')'
    return polygon

class MultiPolygon(Node):
	def __call__(self, model, resource):
		from django.contrib.gis.geos import fromstr
		q = """
SELECT DISTINCT ?coords {
    <%s> <%s> _:seq .
    _:seq <http://sweet.jpl.nasa.gov/1.1/space.owl#Polygon> ?coords
}
""" % (resource.uri, self.uri)
		polygons = []
		for r in SPARQLQuery(q).execute(model):
			polygons.append('(' + coordinates_wkt(r["coords"]) + ')')
		if polygons:
			wkt = 'MULTIPOLYGON(' + ', '.join(polygons) + ')'
			return fromstr(wkt)
		
class Polygon(MultiPolygon):
	def __call__(self, model, resource):
		geom = super(Polygon, self).__call__(model, resource)
		if geom:
			if len(geom) > 1:
				return geom.envelope
			if len(geom) == 1:
				return geom[0]
